package com.nlelpct.manage.controller;

import com.nlelpct.manage.constant.ResponseCode;
import com.nlelpct.manage.model.query.TerminalInfo;
import com.nlelpct.manage.model.query.UserChangePasswordQuery;
import com.nlelpct.manage.model.vo.EmployeeAndCompanyInfoVo;
import com.nlelpct.manage.model.vo.ResponseResult;
import com.nlelpct.manage.service.IUserService;
import com.nlelpct.manage.service.IValidateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author :小马
 * @date : 2023-07-20
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    private final IValidateService validateService;

    private final IUserService userService;

    @Autowired
    public UserController(IValidateService validateService, IUserService userService) {
        this.validateService = validateService;
        this.userService = userService;
    }

    /**
     * 保存IP等信息
     */
    @PostMapping(value = "/terminal")
    public ResponseResult<String> saveTerminalInfo(@RequestBody TerminalInfo info) {
        return validateService.saveTerminalInfo(info);
    }

    /**
     * 登陆成功后查询企业信息
     */
    @PreAuthorize("hasRole('admin')")
    @GetMapping(value = "/listCompany")
    public ResponseResult<List<EmployeeAndCompanyInfoVo>> listCompany() {
        return userService.listCompany();
    }

    /**
     * 用户修改密码 -- 已经登录的情况下
     */
    @PreAuthorize("hasRole('admin')")
    @PostMapping("/changePassword")
    public ResponseResult<String> changePassword(@RequestBody UserChangePasswordQuery changePasswordQuery) {
        try {
            return userService.changeUserPassword(changePasswordQuery);
        } catch (Exception e) {
            log.error("用户修改密码时出现异常,具体异常信息如下: ");
            e.printStackTrace();
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "修改密码失败,请联系系统管理员");
        }
    }


    /**
     * 用户修改密码 -- 用户未登录的情况
     */
    @PostMapping("/noLogin/changePassword")
    public ResponseResult<String> noLoginChangePassword(@RequestBody UserChangePasswordQuery changePasswordQuery) {
        // todo 缺少短信验证
        try {
            return userService.changeUserPassword(changePasswordQuery);
        } catch (Exception e) {
            log.error("用户修改密码时出现异常,具体异常信息如下: ");
            e.printStackTrace();
            return ResponseResult.error(ResponseCode.ORDINARY_FAIL, "修改密码失败,请联系系统管理员");
        }
    }

}
